package com.clannad.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.clannad.commonutils.R;
import com.clannad.servicebase.exceptionhandler.GuliException;
import com.clannad.vod.service.VodService;
import com.clannad.vod.util.ConstantVodUtils;
import com.clannad.vod.util.InitVodClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/eduvod/video")
@Api(tags = {"文件上传"})
//@CrossOrigin
public class VodController {

    @Autowired
    VodService vodService;

    @PostMapping("uploadAliyunVideo")
    @ApiOperation("文件上传")
    public R uploadAliyunVideo(MultipartFile file){
        String videoId=vodService.uploadAliyunVideo(file);
        return R.ok().data("videoId",videoId);
    }

    @DeleteMapping("removeAliyunVideo/{id}")
    @ApiOperation("文件删除")
    public R removeAliyunVideo(@PathVariable String id){
        try{
            DefaultAcsClient defaultAcsClient = InitVodClient.initVodClient(ConstantVodUtils.KEY_ID,ConstantVodUtils.KEY_SECRET);
            DeleteVideoRequest request=new DeleteVideoRequest();
            request.setVideoIds(id);
            defaultAcsClient.getAcsResponse(request);
            return R.ok();
        }catch (Exception e){
            e.printStackTrace();
            throw new GuliException(20001,"删除失败");
        }
    }

    @DeleteMapping("deleteBatch")
    @ApiOperation("多文件删除")
    public R deleteBatch(@RequestParam("videoIds") List<String> videoIds){
        vodService.removeAliyunVideos(videoIds);
        return R.ok();
    }

    //获取播放凭证
    @GetMapping("getPlayAuth/{id}")
    public R getPlayAuth(@PathVariable String id){
        try {
            DefaultAcsClient client= InitVodClient.initVodClient(ConstantVodUtils.KEY_ID, ConstantVodUtils.KEY_SECRET);
            GetVideoPlayAuthRequest request =new GetVideoPlayAuthRequest();
            request.setVideoId(id);
            GetVideoPlayAuthResponse acsResponse = client.getAcsResponse(request);
            String playAuth = acsResponse.getPlayAuth();
            return R.ok().data("playAuth",playAuth);
        } catch (ClientException e) {
            throw new GuliException(20001,"播放失败");
        }

    }
}
